package com.marketingexpert.controller.streammgnt;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.marketingexpert.domain.Keyword;
import com.marketingexpert.domain.Panel;
import com.marketingexpert.domain.Tab;
import com.marketingexpert.service.snsmgnt.SnsService;
import com.marketingexpert.service.snsmgnt.SnsServiceFactory;
import com.marketingexpert.service.streammgnt.StreamService;
import com.marketingexpert.util.Resources;

public class LoadExistThemeController implements Controller {

	private static final Logger logger = Logger.getLogger(LoadExistThemeController.class);
	
	private StreamService streamService;
	
	private SnsServiceFactory snsServiceFactory;
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		response.setContentType("application/x-json;charset=GBK"); 
		response.setHeader("Pragma", "No-cache"); 
		response.setHeader("Cache-Control", "no-cache"); 
		response.setHeader("Cache-Control", "no-store"); 
		response.setDateHeader("Expires", 0);  
		PrintWriter out = response.getWriter();
		
		String tabId = request.getParameter("tabId");
		Assert.notNull(tabId);
		Tab tab = streamService.queryTabById(Integer.parseInt(tabId));
		
		List<Panel> panels = tab.getPanels();
		
		for(Panel panel:panels) {
			Keyword keyword = streamService.queryKeywordsByPanelId(panel.getId());
			panel.setKeyword(keyword);
		}
		
		if(panels == null) {
			logger.warn(Resources.getString("LoadExistThemeController.queryPanelByTabIdFailed"));
			return null;
		} else {
			JSONArray panelsArrayJson = JSONArray.fromObject(panels);
			out.print(panelsArrayJson);
			return null;
		}
	}

	public StreamService getStreamService() {
		return streamService;
	}

	public void setStreamService(StreamService streamService) {
		this.streamService = streamService;
	}

	public SnsServiceFactory getSnsServiceFactory() {
		return snsServiceFactory;
	}

	public void setSnsServiceFactory(SnsServiceFactory snsServiceFactory) {
		this.snsServiceFactory = snsServiceFactory;
	}
	
	
}
